package com.desaysv.svview

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout

class ScaleLayout  @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attributeSet, defStyleAttr){
    
    companion object{
        private const val TAG = "ScaleLayout"
    }
    private val rootLayout=FrameLayout(context,attributeSet,defStyleAttr)

    private var width=0
    private var height=0
    private var scaleFactor=-1.0f
    private var scaleDuring=-1

    init {
        attributeSet?.let {
            val typedArray: TypedArray =
                context.obtainStyledAttributes(it, R.styleable.ScaleLayout)
            scaleFactor=typedArray.getFloat(R.styleable.ScaleLayout_scale_factor, 0.8f)
            scaleDuring=typedArray.getInt(R.styleable.ScaleLayout_scale_during, 100)
            typedArray.recycle()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        width=MeasureSpec.getSize(widthMeasureSpec)
        height=MeasureSpec.getSize(heightMeasureSpec)
    }
    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if(event.action== MotionEvent.ACTION_DOWN){
            rootLayout.animate().scaleX(scaleFactor).scaleY(scaleFactor).setDuration(scaleDuring.toLong()).start()
        }
        if(event.action== MotionEvent.ACTION_UP){
            rootLayout.animate().scaleX(1f).scaleY(1f).setDuration(scaleDuring.toLong()).start()
        }
        rootLayout.dispatchTouchEvent(event)
        return true
    }
    @SuppressLint("ClickableViewAccessibility")
    override fun onFinishInflate() {
        super.onFinishInflate()

        val childrenCount=this.childCount
        val children=ArrayList<View>()
        for(i in 0 until childrenCount){
            val child=this.getChildAt(i)
            children.add(child)
        }
        this.removeAllViews()
        val layoutParams = LayoutParams(
            android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
            android.widget.LinearLayout.LayoutParams.MATCH_PARENT
        )
        this.addView(rootLayout,layoutParams)
        for (child in children) {
            rootLayout.addView(child)
        }
    }
}